package vell.velllock.database;

import java.util.ArrayList;
import java.util.List;

import vell.velllock.object.WordDBInfo;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class WordDBInfoOperator {
	private Context mContext;
	private SQLiteDatabase wordDBInfo;
	public WordDBInfoOperator(Context context){
		mContext = context;
		wordDBInfo = new WordDBInfoOpenHelper(mContext).getWritableDatabase();
	}
	
	public List<WordDBInfo> getWordDBInfos(){
		String sql = "select * from WordDBInfo";
		Cursor cursor = wordDBInfo.rawQuery(sql, null);
		
		return cursorToList(cursor);
	}
	
	public WordDBInfo getActiveWordDBInfo(){
		String sql = "select * from WordDBInfo where active=1";
		Cursor cursor = wordDBInfo.rawQuery(sql, null);
		List<WordDBInfo> WDIs = cursorToList(cursor);
		if(WDIs == null) return null;
		else return WDIs.get(0);
	}
	
	public long getCount(){
		String sql = "SELECT COUNT(*) FROM WordDBInfo";
	    SQLiteStatement statement = wordDBInfo.compileStatement(sql);
	    long count = statement.simpleQueryForLong();
	    return count;
	}
	
	public void updateWordDBInfoByDBFile(WordDBInfo WDI){
		String sql = "update WordDBInfo set " +
				"DBName='" + WDI.getDBName() +
				"', info='" + WDI.getInfo() + 
				"', wordNum=" + WDI.getWordNum() +
				", active=" + WDI.getActive() + 
				" where DBFile='" + WDI.getDBFile() +"'";
		wordDBInfo.execSQL(sql);
	}
	
	public boolean insertDBInfo(WordDBInfo WDI){
		String sql = "insert into WordDBInfo (DBName, info, wordNum, DBFile, active) values('" +
				WDI.getDBName() + "','" +
				WDI.getInfo() + "'," +
				WDI.getWordNum() + ",'" +
				WDI.getDBFile() + "'," +
				WDI.getActive() + ")";
		Log.i("insert sql", sql);
		try{
			wordDBInfo.execSQL(sql);
		} catch(SQLException e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	private List<WordDBInfo> cursorToList(Cursor cursor){
		List<WordDBInfo> WDIList = new ArrayList<WordDBInfo>();
		if(cursor.moveToFirst() == false) return null;
		do{
			WordDBInfo WDI = new WordDBInfo();
			WDI.setId(cursor.getInt(0));
			WDI.setDBName(cursor.getString(1));
			WDI.setInfo(cursor.getString(2));
			WDI.setWordNum(cursor.getInt(3));
			WDI.setDBFile(cursor.getString(4));
			WDI.setActive(cursor.getInt(5));
			WDIList.add(WDI);
		}while(cursor.moveToNext());
		
		return WDIList;
	}
}
